import axios from "axios";
import api from "@/api/index.js";
import { userInfoStore } from "@/store";
import { ElMessage } from "element-plus";

const userInfo = userInfoStore();
const server = axios.create({
  baseURL:
    import.meta.env.MODE === "production"
      ? import.meta.env.VITE_APP
      : import.meta.env.VITE_PATHNAME,
  timeout: 1000,
});
server.interceptors.request.use(
  function (config) {
    userInfo.getToken && (config.headers.token = userInfo.getToken);
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

server.interceptors.response.use(
  function (response) {
    const data = response.data;
    ElMessage({
      type: data.type,
      message: data.message,
    });
    return response;
  },
  function (error) {
    ElMessage({
      type: "error",
      message: error.message,
    });
    return Promise.reject(error);
  }
);
const getServer = (url, params) => {
  return server({
    method: "get",
    url: api[url],
    params: params,
  });
};
const postServer = (url, data, params) => {
  return server({
    method: "post",
    url: api[url],
    data: data,
    params: params,
  });
};
export { getServer, postServer };
